package com.kgc.crowd.distributioncrowdwebui.controller;

import com.kgc.crowd.distributioncrowdcommon.api.MemberManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.api.ProjectManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.pojo.MemberLaunchInfoPO;
import com.kgc.crowd.distributioncrowdcommon.pojo.ResultEntity;
import com.kgc.crowd.distributioncrowdcommon.pojo.TypePO;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdConstant;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdUtils;
import com.kgc.crowd.distributioncrowdcommon.util.UploadUtil;
import com.kgc.crowd.distributioncrowdcommon.vo.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/project/manager")
public class ProjectController {
    @Value("${oss.file.endpoint}")
    String endpoint;
    @Value("${oss.file.accessKeyId}")
    String accessKeyId;
    @Value("${oss.file.accessKeySecret}")
    String accessKeySecret;
    @Value("${oss.file.bucketName}")
    String bucketName;
    @Value("${oss.file.headPictureFolderName}")
    String headPictureFolderName;
    @Value("${oss.file.detailPictureFolderName}")
    String detailPictureFolderName;
    @Value("${oss.file.domain}")
    String domain;
    @Value("${oss.file.retirnFolderName}")
    String retirnFolderName;
    @Resource
    ProjectManagerRemoteService projectManagerRemoteService;
    @Resource
    MemberManagerRemoteService memberManagerRemoteService;


    @RequestMapping("to/start")
    public String tostart() {
        return "start";
    }

    @RequestMapping("/to/startstep1")
    public String tostartstep1(HttpSession session, Model model) {
        //获取登录状态
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj==null){
            return "redirect:/to/login.html";
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO) obj;
        String token=memberSignSuccessVO.getToken();
        //加载分类信息
        ResultEntity<List<TypePO>> typePOResultEntity = projectManagerRemoteService.selectAllType();
        model.addAttribute(CrowdConstant.ATTR_NAME_TYPEPO_LIST,typePOResultEntity.getData());
        //加载标签信息
        ResultEntity<List<TagVO>> allTag = projectManagerRemoteService.selectAllTag();
        model.addAttribute(CrowdConstant.ATTR_NAME_TAG_LIST,allTag.getData());
        //回显发起人信息.
        ResultEntity<MemberLaunchInfoPO> memberLaunchInfoPOResultEntity = memberManagerRemoteService.retrieveMemberLaunchInfoPOByMemberToken(token);
        model.addAttribute(CrowdConstant.ATTR_NAME_MEMBERLAUNCHINFO,memberLaunchInfoPOResultEntity.getData());
        //初始化ProjectVo
        ResultEntity<ProjectVO> projectVOResultEntity=projectManagerRemoteService.initCreation(token);
        if (projectVOResultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,projectVOResultEntity.getMessage());

            return "redirect:/project/manager/start";
        }
        //把projectVo存入Session
        session.setAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT,projectVOResultEntity.getData());

        return "start-step-1";
    }

    //上传头图
    @RequestMapping("/upload/head/picture")
    @ResponseBody
    public ResultEntity<String> uploadHeadPicture(MultipartFile headerPicture, HttpSession session) throws IOException {
        //验证是否登录
        Object obj=session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)obj;
        String memberSignToken=memberSignSuccessVO.getToken();

        Object obj2=session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2==null){
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        ProjectVO projectVO=(ProjectVO)obj2;
        String projectTempToken=projectVO.getProjectTempToken();

        //验证是否选择文件
        if(headerPicture==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        //获取旧的文件名生成新的文件名
        String originalFilename=headerPicture.getOriginalFilename();
        String fileName= UploadUtil.generateFileName(originalFilename);
        //把文件对象换成文件流
        InputStream inputStream=headerPicture.getInputStream();
        //文件上传
        UploadUtil.uploadSingleFile(endpoint,accessKeyId,accessKeySecret,fileName,headPictureFolderName,bucketName,inputStream);
        //保存头图路径redis
        String headPicturePath=domain+"/"+headPictureFolderName+"/"+fileName;
        ResultEntity<String> stringResultEntity = projectManagerRemoteService.saveHeadPicturePath(memberSignToken, projectTempToken, headPicturePath);

        return stringResultEntity;
    }

    //上传详情图
    @RequestMapping("/upload/detail/picture")
    @ResponseBody
    public ResultEntity<String> uploadDetailPicture(
            @RequestParam("detailPicture") List<MultipartFile> detailPictureList,
            HttpSession session) throws IOException{
        //验证是否登录
        Object obj=session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)obj;
        String memberSignToken=memberSignSuccessVO.getToken();
        //验证集合是否为空
        if (CrowdUtils.collectionEffectiveCheck(detailPictureList)==false){
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }

        List<String> detailPicturePathList=new ArrayList<>();
        for (MultipartFile multipartFile : detailPictureList){
            boolean empty=multipartFile.isEmpty();
            if (empty){
                continue;
            }
            String originalFilename=multipartFile.getOriginalFilename();
            String fileName=UploadUtil.generateFileName(originalFilename);
            InputStream inputStream=multipartFile.getInputStream();
            UploadUtil.uploadSingleFile(endpoint,accessKeyId,accessKeySecret,fileName,detailPictureFolderName,bucketName,inputStream);
            String detailPricturePath=domain+"/"+headPictureFolderName+"/"+fileName;
            detailPicturePathList.add(detailPricturePath);
        }
        Object obj2=session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2==null){
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        ProjectVO projectVO=(ProjectVO)obj2;
        String projectTempToken=projectVO.getProjectTempToken();

        ResultEntity<String> stringResultEntity = projectManagerRemoteService.saveDetailPicturePathList(memberSignToken, projectTempToken, detailPicturePathList);
        return stringResultEntity;
    }
    @RequestMapping("/save/project/information")
    @ResponseBody
    public ResultEntity<String> saveProjectInformation(ProjectVO projectVO,HttpSession session){
        MemberSignSuccessVO signVO=(MemberSignSuccessVO)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(signVO==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        projectVO.setMemberSignToken(signVO.getToken());
        ProjectVO project=(ProjectVO)session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        projectVO.setProjectTempToken(project.getProjectTempToken());
        ResultEntity<String> resultEntity = projectManagerRemoteService.saveProjectInformation(projectVO);
        return resultEntity;

    }

    @RequestMapping("/to/project/return")
    public String tostartstep2(){
        return "start-step-2";
    }

    @RequestMapping("/save/return/vo")
    public String saveReturnVO(ReturnVO returnVO,
                               @RequestParam("describPic") MultipartFile describPic,
                               Model model,
                               HttpSession session) throws IOException {
        //验证是否登录
        Object obj=session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)obj;
        String memberSignToken=memberSignSuccessVO.getToken();

        Object obj2=session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"请同意协议");
            return "start";
        }
        ProjectVO projectVO=(ProjectVO)obj2;
        String projectTempToken=projectVO.getProjectTempToken();
        //验证是否选择文件
        if(describPic==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_NO_FILE);
            return "start-step-2";
        }
        //获取旧的文件名生成新的文件名
        String originalFilename=describPic.getOriginalFilename();
        String fileName=UploadUtil.generateFileName(originalFilename);
        //把文件对象换成文件流
        InputStream inputStream=describPic.getInputStream();
        //文件上传
        UploadUtil.uploadSingleFile(endpoint,accessKeyId,accessKeySecret,fileName,retirnFolderName,bucketName,inputStream);
        returnVO.setDescribPicPath(domain+"/"+retirnFolderName+"/"+fileName);

        returnVO.setMemberSignToken(memberSignToken);
        returnVO.setProjectTempToken(projectTempToken);
        ResultEntity<String> resultEntity = projectManagerRemoteService.saveReturnVO(returnVO);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "start-step-2";
        }
        return "start-step-3";
    }

    @RequestMapping("/save/confirm/info/vo")
    public String saveConfirmInfoVO(ReturnVO returnVO,
                                    Model model,
                                    HttpSession session,
                                    MemberConfirmInfoVO vo) throws IOException{
        //验证是否登录
        Object obj=session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO)obj;
        String memberSignToken=memberSignSuccessVO.getToken();

        Object obj2=session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2==null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"请同意协议");
            return "start";
        }
        ProjectVO projectVO=(ProjectVO)obj2;
        String projectTempToken=projectVO.getProjectTempToken();

        vo.setMemberSignToken(memberSignToken);
        vo.setProjectTempToken(projectTempToken);
        ResultEntity<String> resultEntity = projectManagerRemoteService.saveMemberConfirmInfoVO(vo);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "start-step-3";
        }

        ResultEntity<String> databaseEntity = projectManagerRemoteService.saveWholeProject(memberSignToken, projectTempToken);
        if (databaseEntity.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, databaseEntity.getMessage());
            return "start-step-3";
        }

        return "start-step-4";

    }



}
